package enemies.strategy.concretes;

import mapControl.Celda;
import mapControl.MapControl;
import net.datastructures.Dijkstra;
import net.datastructures.Edge;
import net.datastructures.Graph;
import net.datastructures.NodeStack;
import net.datastructures.Vertex;
import elementos.Player;
import enemies.Enemy;
import enemies.strategy.Strategy;

public class ConcreteStrategyInsane implements Strategy {

	protected Object WEIGHT = new Object();
	private Player player;
	private Enemy enemy;

	private Vertex<Celda>[][] mapGraph;

	private Graph<Celda, Integer> graph;
	private NodeStack<Vertex<Celda>> path;
	private Dijkstra<Celda, Integer> dijtra;
	private boolean live;

	public ConcreteStrategyInsane(MapControl mapcontrol, Enemy enemy,
			Player player) {
		this.enemy = enemy;
		this.player = player;
		live = true;
		graph = mapcontrol.getGraph();
		mapGraph = mapcontrol.getMapg();

		for (Edge<Integer> e : graph.edges()) {
			e.put(WEIGHT, 1);
		}

		dijtra = new Dijkstra<Celda, Integer>();

		update();

	}

	private void update() {

		int row = player.getRow();
		int col = player.getCol();
		path = new NodeStack<Vertex<Celda>>();
		if (!(enemy.getRow() == row && enemy.getCol() == col)) {
			int dis = Integer.MAX_VALUE;
			Vertex<Celda> u = mapGraph[enemy.getRow()][enemy.getCol()];
			dijtra.execute(graph, u, WEIGHT);
			dis = dijtra.getDist(mapGraph[row][col]);

			if (dis != Integer.MAX_VALUE) {
				while (dis != 1) {
					path.push(mapGraph[row][col]);

					if (dijtra.getDist(mapGraph[row - 1][col]) == dis - 1)
						row--;
					else if (dijtra.getDist(mapGraph[row + 1][col]) == dis - 1)
						row++;
					else if (dijtra.getDist(mapGraph[row][col - 1]) == dis - 1)
						col--;
					else if (dijtra.getDist(mapGraph[row][col + 1]) == dis - 1)
						col++;
					dis--;
				}
			} else {

			}
		} else {
			System.out.print("teMate");
			live = false;
		}

	}

	@Override
	public boolean execute() {
		if (!path.isEmpty()) {
			Vertex<Celda> myVertex = path.pop();
			int row = myVertex.element().getRow();
			int col = myVertex.element().getCol();
			if (mapGraph[row][col].element().getBomba() != null)
			{
				update();
			}else enemy.moverA(row, col);
		} else update();
		return live;

	}

}